package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Cart;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.tju.elm.service.CartService;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping
    public HttpResult create(@RequestBody Cart cart) {
        boolean saved = cartService.save(cart);
        return saved ? HttpResult.ok(cart) : HttpResult.fail("创建失败");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Integer id, @RequestBody Cart cart) {
        cart.setId(id);
        boolean updated = cartService.updateById(cart);
        return updated ? HttpResult.ok(cart) : HttpResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Integer id) {
        boolean removed = cartService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("删除失败");
    }

    @GetMapping("/{id}")
    public HttpResult get(@PathVariable Integer id) {
        Cart cart = cartService.getById(id);
        return cart != null ? HttpResult.ok(cart) : HttpResult.fail("不存在");
    }

    @GetMapping("/list")
    public HttpResult list(@RequestParam(required = false) Integer userId,
                       @RequestParam(required = false) Integer orderId,
                       @RequestParam(required = false) Integer status,
                       @RequestParam(defaultValue = "1") long page,
                       @RequestParam(defaultValue = "10") long size) {
        QueryWrapper<Cart> qw = new QueryWrapper<>();
        if (userId != null) {
            qw.eq("user_id", userId);
        }
        if (orderId != null) {
            qw.eq("order_id", orderId);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        Page<Cart> p = cartService.page(new Page<>(page, size), qw);
        return HttpResult.ok(p);
    }
}


